package com.sm.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.sm.annotation.IgnoreAuth;
import com.sm.model.*;
import com.sm.service.*;
import com.sm.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DealerService dealerService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private AllianceService allianceService;
    @Autowired
    private ApplyTraditionalService applyTraditionalService;


    /**
     * 短信验证
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    @IgnoreAuth
    @RequestMapping("/checkCode")
    @ResponseBody
    public Msg checkCode(String phone, String code) {
        if (phone == null || code == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        String msg = CommonUtil.verifyMobileCode(phone, code);
        if (msg != null) {
            return Msg.fail().add("msg", msg);
        }
        return Msg.success().add("msg", "登录成功");
    }

    /**
     * 短信接口
     *
     * @param type    1是注册 2是找回密码，3修改绑定手机,5身份确认
     * @param request
     * @return
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("/getCode")
    public Msg getCode(String phone, String type, HttpServletRequest request) {
        if (phone == null || "".equals(phone) || type == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        String smsTpl = null;
//        if (type.equals("1")) {
        // 通用短信模板
        smsTpl = SendMSMUtil.COMMON_TEMPLATE;
//        } else if (type.equals("2")) {
//            smsTpl = SendMSMUtil.COMMON_TEMPLATE_UPDATE;
//        } else if (type.equals("5")) {
//            smsTpl = SendMSMUtil.COMMON_TEMPLATE_IMPORT;
//        } else {
//            smsTpl = SendMSMUtil.COMMON_TEMPLATE_CHECK;
//        }
        try {
            SMSBean smsBean = SendMSMUtil.sendMSM(phone, smsTpl, null);
            if (smsBean == null) {
                return Msg.fail().add("msg", "短信发送失败");
            } else {
                return Msg.success();
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return Msg.fail().add("msg", "短信发送失败");
        }
    }

    /**
     * 注册
     *
     * @param phone          手机号
     * @param code           验证码
     * @param password       密码base64
     * @param recommendCoded 别人的推荐码
     * @return
     */
    @IgnoreAuth
    @RequestMapping("/register")
    @ResponseBody
    public Msg register(String phone, String code, String password, String recommendCoded) {
        if (phone == null || code == null || password == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        String msg = CommonUtil.verifyMobileCode(phone, code);
        if (msg != null) {
            return Msg.fail().add("msg", msg);
        }
        User findUser = userService.selectByPhone(phone);
        if (findUser != null) {
            return Msg.fail().add("msg", "该手机号已被注册，请找回密码！");
        }
        if (StrUtil.isEmpty(recommendCoded)) {
            recommendCoded = "131419";
        }
        User user = new User();

        user.setPhone(phone);
        user.setPassword(password);
        String recommendCode = RandomUtil.randomInt(131419, 999999) + "";
        while (userService.selectByRecommendCode(recommendCode) != null) {
            recommendCode = RandomUtil.randomInt(131419, 999999) + "";
        }
        user.setHeadLink("http://vod.xof.cn/image/default/0EBBDE09FE4140AB86A14F44E385A5BF-6-2.jpeg");

        // 设置我的推荐码
        user.setRecommendCode(recommendCode);
        // 根据推荐码找到我的推荐人
        User referees = userService.selectByRecommendCode(recommendCoded);
        if (referees != null) {
            user.setRefereesUserId(referees.getUserId());
        }
//        //注册成功时在用户身份表初始化一条记录
//        userIdentityService.initUserIdentity(user.getUserId());
        userService.insertSelective(user);
        return Msg.success().add("msg", "注册成功！").add("user", user);

    }

    /**
     * APP内扫码添加推荐人
     */
    @RequestMapping("/addReferees")
    @ResponseBody
    public Msg addReferees(Integer userId, String refereesStr) {

        User user = userService.selectByPrimaryKey(userId);
//        if (user.getRefereesUserId() != null) {
//            //有真的上级
//            if (user.getHasRealParent().equals(1)) {
//                return Msg.fail().add("msg", "已经有推荐人，不能更换");
//            }
//        }

        User referees = userService.selectByRecommendCode(refereesStr);
        if (ObjectUtils.isEmpty(referees)) {
            return Msg.fail().add("msg", "推荐码无效");
        }
        int i = userService.addReferees(userId, referees.getUserId());
        if (i == 1) {
            return Msg.success();
        }
        return Msg.fail().add("msg", "添加推荐人失败");
    }


    /**
     * APP登录（前端MD5加密）
     *
     * @param phone    手机号
     * @param password 密码
     * @return
     */
    @IgnoreAuth
    @RequestMapping(value = "/appLogin")
    @ResponseBody
    public Msg appLogin(String phone, String password) {
        System.out.println("====" + phone);
        System.out.println("====" + password);

        if (StrUtil.isEmpty(phone) || StrUtil.isEmpty(password)) {
            return Msg.fail().add("msg", "账号或密码不空！");
        }
        User findUser = userService.selectByPhone(phone);
        if (findUser == null) {
            return Msg.fail().add("msg", "账号不存在！");
        }
        if (!password.equals(findUser.getPassword())) {
            return Msg.fail().add("msg", "密码不正确！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("account", phone);
        //登录设置新的token
        String token = IdUtil.simpleUUID();
        findUser.setToken(token);
        userService.updateByPrimaryKeySelective(findUser);
        return Msg.success().add("user", findUser).add("token", token);
    }

    /**
     * 忘记密码
     *
     * @param phone       手机号
     * @param code        验证码
     * @param newPassword 新密码
     * @return
     */
    @IgnoreAuth
    @RequestMapping("/updatePassword")
    @ResponseBody
    public Msg updatePassword(String phone, String code, String newPassword) {
        if (phone == null || code == null || newPassword == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        String msg = CommonUtil.verifyMobileCode(phone, code);
        if (msg != null) {
            return Msg.fail().add("msg", msg);
        }
        User user = userService.selectByPhone(phone);
        if (user == null) {
            return Msg.fail().add("msg", "该手机号码未注册，无法修改！");
        }

        user.setPassword(newPassword);
        int a = userService.updateByPrimaryKeySelective(user);
        if (a == 1) {
            return Msg.success();
        } else {
            return Msg.fail().add("msg", "修改失败！");
        }
    }

    /**
     * 修改手机密码
     *
     * @param code        验证码
     * @param newPassword 新密码
     * @return
     */
    @RequestMapping("/editPassword")
    @ResponseBody
    public Msg editPassword(Integer userId, String code, String oldPassword, String newPassword) {
        if (userId == null || code == null || oldPassword == null || newPassword == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        System.out.println("=========*" + userId);
        User user = userService.selectByPrimaryKey(userId);

        System.out.println("=========2" + user.getPhone());
        String msg = CommonUtil.verifyMobileCode(user.getPhone(), code);
        if (msg != null) {
            return Msg.fail().add("msg", msg);
        }
        String pw = user.getPassword();//获取原密码
        if (!oldPassword.equals(pw)) {
            return Msg.fail().add("msg", "请输入正确原密码");
        }

        if (newPassword.equals(pw)) {
            return Msg.fail().add("msg", "新密码不能是原密码");
        } else {
            user.setPassword(newPassword);
        }

        int a = userService.updateByPrimaryKeySelective(user);
        if (a == 1) {
            return Msg.success();
        } else {
            return Msg.fail().add("msg", "修改失败！");
        }
    }

    /**
     * 修改支付密码
     *
     * @param userId
     * @param code
     * @param oldPayPassword
     * @param newPayPassword
     * @return
     */
    @RequestMapping("/editPayPassword")
    @ResponseBody
    public Msg editPayPassword(Integer userId, String code, String oldPayPassword, String newPayPassword) {
        if (userId == null || code == null || oldPayPassword == null || newPayPassword == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        System.out.println("=========*" + userId);
        User user = userService.selectByPrimaryKey(userId);

        System.out.println("=========2" + user.getPhone());
        String msg = CommonUtil.verifyMobileCode(user.getPhone(), code);
        if (msg != null) {
            return Msg.fail().add("msg", msg);
        }

        String pw = user.getPayPassword();//获取原密码
        if (!oldPayPassword.equals(pw)) {
            return Msg.fail().add("msg", "请输入正确原密码");
        }

        if (newPayPassword.equals(pw)) {
            return Msg.fail().add("msg", "新密码不能是原密码");
        } else {
            user.setPayPassword(newPayPassword);
        }

        int a = userService.updateByPrimaryKeySelective(user);
        if (a == 1) {
            return Msg.success();
        } else {
            return Msg.fail().add("msg", "修改失败！");
        }
    }

    /**
     * 编辑个人信息
     *
     * @param userId
     * @param headlink
     * @param nickname
     * @param sex
     * @param birth
     * @param area
     * @return
     */
    @RequestMapping("/editUser")
    @ResponseBody
    public Msg editUser(Integer userId, @RequestParam("headlink") String headlink, @RequestParam("nickname") String nickname,
                        @RequestParam(value = "sex",required = false)  Integer sex,@RequestParam(value = "birth",required = false)  String birth,
                        @RequestParam(value = "area",required = false) String area) {
        if (userId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        // 根据userId查询当前用户表
        User user = userService.selectByPrimaryKey(userId);
        //头像
        user.setHeadLink(headlink);
        // 昵称
        user.setNickName(nickname);
        // 性别
        user.setSex(sex);
        // 出生年月日
        user.setBirth(birth);
        // 地区
        user.setArea(area);
        int a = userService.updateByPrimaryKeySelective(user);
        if (a == 1) {
            return Msg.success().add("msg", "保存成功").add("user", user);
        } else {
            return Msg.fail().add("msg", "保存失败");
        }
    }

    /**
     * 申请成为区域经理
     *
     * @param
     * @return
     */
    @RequestMapping("/editDealer")
    @ResponseBody
    public Msg editDealer(@RequestParam("userName") String userName,
                          @RequestParam("userSex") Integer userSex,
                          @RequestParam("userId") Integer userId,
                          @RequestParam("phone") String phone,
                          @RequestParam("address") String address) {
        if (StrUtil.isEmpty(userName) || userSex == null || userId == null || StrUtil.isEmpty(phone)) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        System.out.println("========" + userName);
        System.out.println("========" + userSex);
        System.out.println("========" + userId);
        System.out.println("========" + phone);
        Dealer dealer = new Dealer();
        dealer.setUserName(userName);
        dealer.setUserId(userId);
        dealer.setUserSex(userSex);
        dealer.setPhone(phone);
        dealer.setCreateTime(new Date());
        dealer.setAddress(address);
        dealer.setStatus(0);
        int a = dealerService.insertSelective(dealer);
        if (a == 1) {
            return Msg.success().add("msg", "提交成功");
        } else {
            return Msg.fail().add("msg", "提交失败");
        }
    }

    @RequestMapping("/applyTraditional")
    @ResponseBody
    public Msg applyTraditional(ApplyTraditional applyTraditional) {
        List<String> typeList = applyTraditional.getTypeList();
        if (typeList == null || typeList.size() == 0) {
            return Msg.fail().add("msg", "请选择类型");
        }
        String types = String.join(",", typeList);
        applyTraditional.setType(types);
        int i = applyTraditionalService.insert(applyTraditional);
        if (i > 0) {
            return Msg.success();
        } else {
            return Msg.fail().add("msg", "错误");
        }
    }

    /**
     * 申请成为联盟园
     *
     * @param userName
     * @param userSex
     * @param userId
     * @param phone
     * @param
     * @return
     */
    @RequestMapping("/insertAlliance")
    @ResponseBody
    public Msg insertAlliance(@RequestParam("userName") String userName,
                              @RequestParam("userSex") Integer userSex,
                              @RequestParam("userId") Integer userId,
                              @RequestParam("phone") String phone,
                              @RequestParam("address") String address) {
        if (userName == null || userSex == null || userId == null || phone == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        System.out.println("========" + userName);
        System.out.println("========" + userSex);
        System.out.println("========" + userId);
        System.out.println("========" + phone);
        Alliance alliance = new Alliance();
        alliance.setUserId(userId);
        alliance.setUserName(userName);
        alliance.setUserSex(userSex);
        alliance.setPhone(phone);
        alliance.setCreateTime(new Date());
        alliance.setAddress(address);
        alliance.setStatus(0);
        int a = allianceService.insertAlliance(alliance);
        if (a == 1) {
            return Msg.success().add("msg", "提交成功");
        } else {
            return Msg.fail().add("msg", "提交失败");
        }
    }



    /**
     * 查询用户(我的账户)
     *
     * @param userId
     * @return
     */
    @RequestMapping("/selectUser")
    @ResponseBody
    public Msg selectUser(Integer userId) {
        if (userId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        // 根据userId查询当前用户表
        User user = userService.selectByPrimaryKey(userId);

        return Msg.success().add("user", user);
    }

    /**
     * 根据 查询收货地址
     *
     * @param userId
     * @return
     */
    @RequestMapping("/selectAddress")
    @ResponseBody
    public Msg selectAddress(Integer userId) {
        if (userId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }

        List<UserAddress> alist = userAddressService.selectByUserId(userId);

        return Msg.success().add("alist", alist);
    }

    /**
     * 添加收货地址
     *
     * @param userId
     * @param userName    收货人姓名
     * @param userPhone   收货人电话
     * @param userAddress 收货人地址
     * @param isDefault   （-1：不是。1：是）
     * @return
     */
    @RequestMapping("/addAddress")
    @ResponseBody
    public Msg addAddress(Integer userId, String userName, String userPhone, String userAddress, String isDefault) {
        if (userId == null || userName == null || userPhone == null || userAddress == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        // 创建一个新对象
        UserAddress uAddress = new UserAddress();
        uAddress.setUserId(userId);
        uAddress.setUserName(userName);
        uAddress.setUserPhone(userPhone);
        uAddress.setUserAddress(userAddress);

        if (isDefault.equals("1")) {
            // 查找当前用户默认地址为1的那条数据
            UserAddress uAddress2 = userAddressService.selectByUidAndIsdefault(userId);
            if (uAddress2 != null) {
                uAddress2.setIsDefault("-1");// 将原来的默认地址消除
                userAddressService.updateByPrimaryKeySelective(uAddress2);
            }
        }
        // 设置新的默认地址
        uAddress.setIsDefault(isDefault);

        int val = userAddressService.insertSelective(uAddress);
        if (val == 1) {
            return Msg.success().add("msg", "添加成功");
        } else {
            return Msg.fail().add("msg", "添加失败");
        }

    }

    /**
     * 获取默认收货地址
     * @param userId
     * @return
     */
    @RequestMapping("/getDefaultAddress")
    @ResponseBody
    public Msg editAddress(Integer userId) {
        if (userId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        UserAddress userAddress = userAddressService.selectByUidAndIsdefault(userId);
        return Msg.success(userAddress);
    }


    /**
     * 编辑收货地址
     *
     * @param userAddressId
     * @param userName
     * @param userPhone
     * @param userAddress
     * @param isDefault
     * @return
     */
    @RequestMapping("/editAddress")
    @ResponseBody
    public Msg editAddress(Integer userId, Integer userAddressId, String userName, String userPhone, String
            userAddress,
                           String isDefault) {
        if (userId == null || userAddressId == null || userName == null || userPhone == null || userAddress == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }

        UserAddress uAddress = userAddressService.selectByPrimaryKey(userAddressId);
        uAddress.setUserName(userName);
        uAddress.setUserPhone(userPhone);
        uAddress.setUserAddress(userAddress);

        if (isDefault.equals("1")) {
            // 查找当前用户默认地址为1的那条数据
            UserAddress uAddress2 = userAddressService.selectByUidAndIsdefault(userId);
            if (uAddress2 != null) {
                uAddress2.setIsDefault("-1");// 将原来的默认地址消除
                userAddressService.updateByPrimaryKeySelective(uAddress2);
            }
        }
        // 设置新的默认地址
        uAddress.setIsDefault(isDefault);

        int val = userAddressService.updateByPrimaryKeySelective(uAddress);
        if (val == 1) {
            return Msg.success().add("msg", "收货地址修改成功");
        } else {
            return Msg.fail().add("msg", "收货地址修改失败");
        }
    }

    /**
     * 删除收货地址
     *
     * @param
     * @return
     */
    @RequestMapping("/deleteAddress")
    @ResponseBody
    public Msg deleteAddress(@RequestParam("userAddressIds") List<Integer> userAddressIds) {
        if (userAddressIds == null) {
            return Msg.fail().add("msg", "参数为空！");
        }
        userAddressService.deleteAddress(userAddressIds.toArray(new Integer[0]));
        return Msg.success().add("msg", "删除成功");

    }


    /**
     * 点击改变默认地址
     *
     * @param userId
     * @param userAddressId
     * @param isDefault
     * @return
     */
    @RequestMapping("/clickChangeAddress")
    @ResponseBody
    public Msg clickChangeAddress(Integer userId, Integer userAddressId, String isDefault) {
        if (userId == null || userAddressId == null || isDefault == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        UserAddress uAddress = userAddressService.selectByPrimaryKey(userAddressId);
        if (isDefault.equals("1")) {
            // 查找当前用户默认地址为1的那条数据
            UserAddress uAddress2 = userAddressService.selectByUidAndIsdefault(userId);

            if (uAddress2 != null) {
                uAddress2.setIsDefault("-1");// 将原来的默认地址消除
                userAddressService.updateByPrimaryKeySelective(uAddress2);
            }
        }
        // 设置新的默认地址
        uAddress.setIsDefault(isDefault);

        int val = userAddressService.updateByPrimaryKeySelective(uAddress);
        if (val == 1) {
            return Msg.success().add("msg", "修改默认地址成功");
        } else {
            return Msg.fail().add("msg", "修改默认地址失败");
        }

    }

    /**
     * 更改上级
     *
     * @param userId
     * @return
     */
    @RequestMapping("/updateParentById")
    @ResponseBody
    public Msg updateParentById(@RequestParam("userId") Integer userId, @RequestParam("recommendCode") String
            recommendCode) {
        //查询下级
        User user = userService.selectUserById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return Msg.fail().add("msg", "用户不存在");
        }
        //查询上级
        User userSecond = userService.selectByCode(recommendCode);
        if (ObjectUtil.isEmpty(userSecond)) {
            return Msg.fail().add("msg", "用户不存在");
        }
        if (userSecond.getUserId().equals(userId)) {
            return Msg.fail().add("msg", "不能绑定自己");
        }
        int i = userService.addReferees(userId, userSecond.getUserId());
        if (i == 1) {
            return Msg.success().add("Msg", "更改成功");
        }

        return Msg.success().add("Msg", "更改失败");
    }

}
